package com.lin.eventbus.callback;

import com.lin.eventbus.EventChannel
import com.lin.eventbus.EventContext
import com.lin.eventbus.IEventListener
import com.lin.eventbus.annotation.Install
import com.lin.eventbus.annotation.Singleton

@Singleton
class CallbackIEventListener private constructor() : IEventListener {

    companion object {
        val INSTANCE = CallbackIEventListener()
    }

    override fun accept(context: EventContext): Boolean {
        return context.event is CallbackEvent
    }

    override fun onEvent(context: EventContext) {
        val event = context.event as CallbackEvent
        val callback = event.callback
        try {
            callback.call()?.run {
                context.setExtension("Callback.Result", this)
            }

        } catch (ex: Throwable) {
            CallbackException.throwException(ex)
        }
    }

    @Install
    @EventChannel("/lin/core")
    class Installer : IEventListener by INSTANCE
}
